const { CARD_GROUP, CARD } = require('./chudadiConstants.js');

// TODO 这里就不该返回对象，应该是boolean
/**
 * 判断打出的牌型是否能跟牌
 * @param {Array.<Number>} playingCards - 当前玩家打出的牌组
 * @param {Array.<Number>} followCards - 跟牌的牌组
 */
function canFollow(playingCards, followCards) {
    let message = ''
    // 锄大地中，牌数量不一致当然不是同一个牌型
    if (playingCards.length !== followCards.length) {
      return {error: true, result: '跟牌与当前打的牌不是同一个牌型，不能跟牌'}
    }
    // 认为playingCards肯定是符合某种牌型的，因为出牌/跟牌的时候已经检测过了
    // 先检测followCards
    const followCardsInfo = calculateCardScore(followCards)
    if (followCardsInfo.type === CARD_GROUP.NONE) {
      return {error: true, result: '跟牌不符合任何牌型'}
    }
    const playingCardsInfo = calculateCardScore(playingCards)
    if (followCardsInfo.score <= playingCardsInfo.score) {
      return {error: true, result: `跟牌牌型不够正在打出的牌型大，打出的牌${playingCards}，跟牌${followCards}`}
    }
    return {error: false, result: '跟牌成功'}
}

/**
 * 识别playingCards的牌型，并计算出分数
 * @param {Array.<Number>} playingCards - 当前玩家打出的牌组，认为传入的是排序后的数组
 * @return {Object} - 形如：{type: <CARD_GROUP>, score: Number}
 */
function calculateCardScore(playingCards) {
  const addon = 200 // 为了让A、2算分时超过K，这里写死一个数字
  const len = playingCards.length
  // 方便后面计算，这里先映射出数字数组、花色数组
  const nums = playingCards.map(card => Math.floor(card / 10))
  const types = playingCards.map(card => Math.floor(card % 10))
  // 将A、2的分数调高后的数组
  const scores = playingCards.map(card => (card < CARD.DIAMOND_3 ? addon : 0) + card)
  scores.sort((a, b) => a - b)
  console.log('calculateCardScore', nums, types, scores, len)
  let ret = {type: CARD_GROUP.NONE, score: 0}
  if (1 <= len && len <= 4) {
    const firstNum = nums[0]
    if (nums.every(num => num === firstNum)) {
      ret.type = len * 1000 // 详见 CARD_GROUP，每种牌型都是1000的倍数
      ret.score = ret.type + scores[len - 1]
    }
  } else if (len === 5) {
    console.log('len === 5')
    if (_isFourWithOne(nums)) { // 4带1
      ret.type = CARD_GROUP.FOUR_WITH_ONE
      ret.score = CARD_GROUP.FOUR_WITH_ONE + scores[2] // 中间那张牌就是4张的牌
    } else if (_isFullHouse(nums)) { // 3带2
      ret.type = CARD_GROUP.FULL_HOUSE
      ret.score = CARD_GROUP.FULL_HOUSE + scores[2] // 中间那张牌就是3张的牌
    } else {
      let isStraight = _isStraight(nums)
      console.log('isStraight', nums, isStraight)
      if (_isFlush(types)) { // 同花
        // 考虑同花顺
        if (isStraight) {
          ret.type = CARD_GROUP.STRAIGHT_FLUSH
          ret.score = CARD_GROUP.STRAIGHT_FLUSH + (nums[0] === CARD.ACE && nums[1] === CARD.TEN ? scores[len - 1] : playingCards[len - 1])
        } else {
          ret.type = CARD_GROUP.FLUSH
          ret.score = CARD_GROUP.FLUSH + scores[len - 1]
        }
      }
      if (isStraight) { // 顺子（除了普通的顺子，考虑A、10、J、Q、K的特殊情况）
        ret.type = CARD_GROUP.STRAIGHT
        ret.score = CARD_GROUP.STRAIGHT + (nums[0] === CARD.ACE && nums[1] === CARD.TEN ? scores[len - 1] : playingCards[len - 1])
      }
    }
  }
  return ret
}

function _isStraight(nums) {
  let start_i = 1
  if (nums[0] === CARD.ACE && nums[1] === CARD.TEN) {
    start_i = 2
  }
  for (let i = start_i; i < 5; i++) {
    if (nums[i] - nums[i - 1] !== 1) {
      return false
    }
  }
  return true
}

function _isFlush(types) {
  return types.every(type => type === types[0])
}

function _isFullHouse(nums) {
  return nums[0] === nums[1] && nums[3] === nums[4] && (nums[1] === nums[2] || nums[2] === nums[3])
}

function _isFourWithOne(nums) {
  return nums[1] === nums[2] && nums[2] === nums[3] && (nums[0] === nums[1] || nums[3] === nums[4])
}

module.exports = {
  canFollow,
  calculateCardScore
};